<?php
namespace app\api\controller;
/*首页控制器*/

use app\common\service\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class Order extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->curl = app('app\common\service\CurlServer');
        $this->store =  app('app\common\model\mall\Store');
        $this->account =  app('app\common\model\mall\Account');
        $this->account_item =  app('app\common\model\media\AccountItem');
        $this->see_history =  app('app\common\model\system\SeeHistory');
        $this->cate =  app('app\common\model\common\Categories');
        $this->collect =  app('app\common\model\common\Collect');
        $this->user =  app('app\common\model\user\WxUsers');
        $this->integral_detail =  app('app\common\model\user\IntegralDetail');
        $this->user_net =  app('app\common\model\media\UserNet');
        $this->topic =  app('app\common\model\media\Topic');
        $this->order =  app('app\common\model\mall\Order');
        $this->order_user_info =  app('app\common\model\mall\OrderUserInfo');
        $this->order_comment =  app('app\common\model\mall\OrderComment');
        $this->comment =  app('app\common\model\media\Comment');
        $this->group_master =  app('app\common\model\mall\GroupMaster');
        $this->group_join =  app('app\common\model\mall\GroupJoin');
        $this->ali_pay = app('app\common\service\AliPay');
        $this->configuration =  app('app\common\model\system\Configuration');
    }

    /**
     * 支付宝支付  //建行支付
     * @param Request $request
     * @return \think\response\Json
     */
    public function pay_order(Request $request)
    {

        $data = $this->order->where(['id'=>$request->param('order_id'),'user_id'=>$request->user_id])->find();
        $order_user_info = $this->order_user_info->where('order_id',$request->param('order_id'))->find();
        if($data->py_URL !=''){

            return json(['code'=>200,'msg'=>'生成成功','data'=>['pay_url'=>$data['py_URL']]]);
        }else{

            if($data->status != 7){
                return json(['code'=>202,'msg'=>'当前订单已支付']);
            }
            //请求java建行支付
            $result['IttParty_Jrnl_No'] = $data->order_sn.rand(1000,9999); //随机生成支付流水号
            $result['Cmdty_Ordr_No'] = $data->order_sn;//商品订单号
            $result['TAmt'] = $data->amount;//金额
            //$result['url'] = 'http://zjjxdcw.gp.mytunnel.site:8029/online/multipenpayment';
            $result['url'] = 'https://zjjxdcw.govpay.ccb.com/online/multipenpayment';
            $result['Cst_Nm'] = $order_user_info->user_name;//客户姓名
            $result['Crdt_No'] = $order_user_info->id_card;//身份证号码
            $result['MblPh_No'] = $order_user_info->mobile;//手机号码

            $result['PgFc_Ret_URL_Adr'] = 'http://www.dcpxjypt.cn/h5/#/pages/mine/ords/ords';
            $json['Fee_Itm_Prj_Amt'] = $data->amount;
            $json['Cmdty_Sub_Ordr_No'] = $data->order_sn.'1';
            $json['Fee_Itm_Cd'] = '330481000001';
            $json['SN'] = 2;
            $result['SendSubInBo1Str'] = '['.json_encode($json).']';

            $datas = $this->curl->curl('47.114.152.142:8083/pay/gotopay',$result);


            if($datas['resultCode'] == 200 ){
                $info['py_Ordr_No'] = $datas['data']['py_Ordr_No'];
                $info['py_URL'] = $datas['data']['py_URL'];
            }
            $this->order->where('id',$request->param('order_id'))->save($info);

            //$ali_pay_info = $this->ali_pay->index($order->order_sn,$order->price,$order->group_id,$order->is_group,$order->type);
            //return json(['code'=>200,'msg'=>'生成成功','data'=>['info'=>$ali_pay_info]]);
            return json(['code'=>200,'msg'=>'生成成功','data'=>['pay_url'=>$datas['data']['py_URL']]]);
        }

    }

    /*对账单推送*/

    public function record()
    {
        // 获取请求文件
        $file = request()->file();
        file_put_contents("test7.txt", $file.'|', FILE_APPEND);
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile( 'zip', $file);

        // 拼接上传后的文件绝对路径
        $uploadPath = str_replace('\\','/','storage/'.$savename);

        // 定义解压路径
        $unzipPath = './uploads/unzip/'.date('Ymd').'/'.basename($uploadPath,".zip");

        // 实例化对象
        $zip = new \ZipArchive();

        //打开zip文档，如果打开失败返回提示信息
        if ($zip->open($uploadPath,\ZipArchive::CREATE) !== TRUE) {
            die ("Could not open archive");
        }else{
            //将压缩文件解压到指定的目录下
            $zip->extractTo($unzipPath);
            //关闭zip文档
            $zip->close();
            //return 'ok';
        }

        //echo '对账单地址';
        $xmldata = file_get_contents("php://input");
        file_put_contents("test7.txt", $unzipPath.date('Y-m-d H:i:s').'|', FILE_APPEND);
    }

    /**
     * 建行回调
     */
    public function test_notify()
    {
        //echo '支付回调';
        $xmldata = file_get_contents("php://input");
        //file_put_contents("test6.txt", $xmldata.'|----|', FILE_APPEND);
        $data = json_decode($xmldata,true);
        try {
            $order_no = $data['Cmdty_Ordr_No'];
            //file_put_contents("test.txt", $order_no.'|', FILE_APPEND);

            $order_info = Db::name('order')->where('order_sn', $order_no)->find();
            //file_put_contents("test.txt", $order_info['type'], FILE_APPEND);

            if ($order_info['type'] == 1) {//网上课程
                $data['amount'] = $order_info['amount'];
                // Net::where('id',$data['goods_id'])->decrement('alone_number',1);
                //增加销量
                Db::name('account')->where('id', $order_info['goods_id'])->inc('sale', 1)->update();
                Db::name('account')->where('id', $order_info['goods_id'])->dec('alone_number', 1)->update();

                Db::name('user_net')->insert(['user_id' => $order_info['user_id'],
                    'net_id' => $order_info['goods_id'], 'type' => 1, 'create_time' => time()]);
                Db::name('order')->where('order_sn', $order_info['order_sn'])->update(['status' => 5]);
            } else {//线下课程
                $info = Db::name('account')->find($order_info['goods_id']);

                //主团id
                $group_id = $order_info['master_group_id'];

                if ($order_info['is_group'] == 1 && ($order_info['group_id'] == $order_info['master_group_id'])) { //开团

                    //自己参团
                    $this->group_join->save (['order_sn'=>$order_no,'is_over' => 1,
                        'user_id'=>$order_info['user_id'],'master_id'=>$order_info['master_group_id']
                    ]);
                    $this->group_master->where('id',$order_info['master_group_id'])->inc('join_number')->update();

                    Db::name('order')->where('order_sn', $order_no)->update(['status' => 0]);
                } else if ($order_info['is_group'] == 1  && $order_info['group_id'] > 0 && $order_info['group_id'] != $order_info['master_group_id']) { //参团
                    //参团数据入库
                    $this->group_join->save (['order_sn'=>$order_no,'is_over' => 1,
                        'user_id'=>$order_info['user_id'],'master_id'=>$order_info['master_group_id']
                    ]);
                    $this->group_master->where('id',$order_info['master_group_id'])->inc('join_number')->update();
                    //查看是否团购人数已满。团成功并结束
                    $group_info = Db::name('group_master')->where('id', $group_id)->field('join_number,total_number')->find();

                    Db::name('order')->where('order_sn', $order_no)->update(['status' => 0]);
                    if ($group_info['join_number'] >= $group_info['total_number']) {
                        Db::name('group_master')->where('id', $order_info['master_group_id'])->update(['is_over' => 1]);
                        //修改订单状态
                        $list = Db::name('group_join')->where('master_id', $order_info['master_group_id'])->select();

                        foreach ($list as $k => $v) {
                            /*设置课程用户拥有*/
                            Db::name('user_net')->insert(['user_id' => $v['user_id'],
                                'net_id' => $order_info['goods_id'], 'type' => 0]);

                            Db::name('order')->where('order_sn',$v['order_no'])->update(['status' =>1]);
                        };
                    }
                } else if($order_info['group_id'] == 0 && $order_info['is_group'] == 0) {//单独购买

                    //file_put_contents("test.txt", $data['trade_no'], FILE_APPEND);
                    /*设置课程用户拥有*/
                   $this->user_net->save(['user_id' => $order_info['user_id'],
                        'net_id' => $order_info['goods_id'], 'type' => 0]);
                    //dd($order_info);
                    Db::name('order')->where('order_sn',$order_no)->update(['status' =>1]);

                }

            }

        } catch (\Exception $e) {

        }

    }

    /*提交订单*/
    public function create_order(Request $request){

        // file_put_contents("test.txt", "Hello world everyone.".PHP_EOL, FILE_APPEND);
        $data = $request->param();
        $prefix = date('Ymd');
        //检查
        try{

            Db::startTrans();
            $data['user_id'] = $request->user_id;
            //普通课程
            if(!$this->account->where(['type'=>2,'id'=>$data['goods_id'],'status'=>1])->find()){
                return json(['code'=>202,'msg'=>'此课程不存在或已下架']);
            }
            //检查库存名额sku是否足够
            if(@$request->param('sku_id') && $this->account_item->where(['article_id'=>$request->param('goods_id'),'id'=>$data['sku_id']])->find()){
                $sku_info = $this->account_item->find($request->param('sku_id'));
                if(!$sku_info){
                    return json(['code'=>202,'msg'=>'此课程规格不存在或已下架']);
                }
            }

            //获取sku

            $info = $this->account->find($data['goods_id']);
            $data['store_id'] = $info->store_id;


            $data['order_sn'] = $prefix.random_int(100000, 999999).$prefix;


            //查看剩余库存
            if($sku_info->number<1){
                return json(['code'=>202,'msg'=>'名额不足']);
            }

            $data['master_group_id'] = $data['group_id'];
            //先检验库存
            if(isset($data['is_group']) && $data['is_group'] == 1 && $data['group_id']==0){

                //if($info->alone_number < $info->num){

                if($sku_info->number < $info->num){
                    return json(['code'=>202,'msg'=>'名额不足']);
                }


            }
            if($data['pay_type'] == 1){//微信支付

                $wechat_pay = new WechatPay;
                $wechat_pay_info = $wechat_pay->index($data['order_sn'],$info->price,$data['is_group'],$data['group_id']);

                $this->account->where('id',$data['goods_id'])->dec('alone_number',1)->update();
                $this->account_item->where('id',$data['sku_id'])->dec('number',1)->update();
                //增加销量
                $this->account->where('id',$data['goods_id'])->inc('sale')->update();

                $order_info = $this->order->save($data);
                Db::commit();
                return json(['code'=>200,'msg'=>'生成成功','data'=>['order_id'=>$order_info->id,'info'=>$wechat_pay_info]]);
            }else{//支付b宝支付

                $data['pay_type'] = 3;

                $data['status'] = 7;
                /* $this->account->where('id',$data['goods_id'])->dec('alone_number',1)->update();
                 //增加销量
                 $this->account->where('id',$data['goods_id'])->inc('sale',1)->update();*/
                /*是否开启团购*/
                if(isset($data['is_group']) && $data['is_group'] == 1 && $data['group_id']==0){

                    if($info->alone_number < $info->num){
                        return json(['code'=>202,'msg'=>'名额不足']);
                    }

                    //发起团
                    $master_group = $this->group_master->save(['order_sn'=>$data['order_sn'],
                        'user_id'=>$request->user_id,'goods_id'=>$data['goods_id'],'total_number'=>$info->num,
                        'join_number'=>0,'is_over'=>0,'end_time'=>time()+86400
                    ]);

                    $data['master_group_id'] =  $this->group_master->id;
                    $master_group_id = $this->group_master->id;
                   /* $this->group_master->where('id',$data['master_group_id'])->inc('join_number')->update();
                    //自己参团
                    $group_id = $this->group_join->save (['order_sn'=>$data['order_sn'],
                        'user_id'=>$request->user_id,'master_id'=>$master_group_id,'create_time'=> time()
                    ]);*/
                    $data['group_id'] =  $this->group_join->id;

                }elseif(isset($data['is_group']) && $data['is_group'] ==1 && $data['group_id'] >0){ //参团的

                    //判断当前团是否自己的
                    if( $this->group_master->where(['user_id'=>$request->user_id,'id'=>$data['group_id']])->find()){
                        return json(['code'=>202,'msg'=>'无法参加自己的团']);
                    } //判断这个团是否已结束
                    else if( !$this->group_master->where(['id'=>$data['group_id'],'is_over'=>0])->find()){
                        return json(['code'=>202,'msg'=>'当前团已结束或不存在']);
                    }else{
                        $data['master_group_id'] =  $data['group_id'];
                        //参团
                       /* $group_id = $this->group_join->save (['order_sn'=>$data['order_sn'],
                            'user_id'=>$data['user_id'],'master_id'=>$data['group_id']
                        ]);*/
                        $data['group_id'] =  $this->group_join->id;
                        /*$this->group_master->inc('join_number')->update();
                        //查看是否团购人数已满。团成功并结束
                        $group_info = $this->group_master->where('id',$data['group_id'])->field('join_number','total_number')->find();

                        if($group_info->join_number >= $group_info->total_number ){
                            $this->group_master->where('id',$data['group_id'])->update(['updated_at'=>date('Y-m-d H:i:s'),'is_over'=>1]);

                        }*/
                    }

                }
                $this->account->where('id',$data['goods_id'])->dec('alone_number',1)->update();
                $this->account_item->where('id',$data['sku_id'])->dec('number',1)->update();
                //增加销量
                $this->account->where('id',$data['goods_id'])->inc('sale')->update();
                $order_info = $this->order->save($data);
                $order_user_info = $this->order_user_info->where(['user_id'=>$data['user_id']])->order('create_time desc')->find();
                Db::commit();
                return json(['code'=>200,'msg'=>'生成成功','data'=>['order_id'=>$this->order->id,'order_user_info'=>$order_user_info/*,'info'=>$ali_pay_info*/]]);
            }
            /*java接口数据*/
            /* $result['IttParty_Jrnl_No'] = '2020'.$data['order_sn'];
             $result['Cmdty_Ordr_No'] = $data['order_sn'];
             $result['TAmt'] = $data['amount'];
             $result['url'] = 'https://ahhfbdc.govpay.ccb.com/online/multipenpayment';

             $json['Fee_Itm_Prj_Amt'] = $data['amount'];
             $json['Cmdty_Ordr_No'] = $data['order_sn'];
             $json['Fee_Itm_Cd'] = 'bgt'.$data['order_sn'];
             $json['SN'] = 1;
             $result['SendSubInBo1Str'] = [json_encode($json)];
             /*java接口数据*/
            // $order_info = $this->order->save($data);*/




            Db::commit();
            return json(['code'=>200,'msg'=>'生成成功','data'=>['java_data'=>$result,'order_id'=>$this->order->id]]);
        }catch (\Exception $exception){
            Db::rollback();
            return json(['code'=>202,'msg'=>'生成失败','data'=>$exception->getMessage()]);
        }
    }


    /*填写用户信息*/
    public function write_info(Request $request){
        $data = $request->param();
        try{
            $data['user_id'] = $request->user_id;

            $rule = [
                'parent|家长姓名'       => 'require',
                'user_name|学生姓名'       => 'require',
                'school|学校姓名' => 'require',
                'id_card|学校身份证' => 'require',
                'age|学校年龄' => 'require',
                'mobile|手机号' => 'require',
            ];
            $this->validate($data, $rule);
            if(!$this->order->where(['user_id'=>$data['user_id'],'id'=>$data['order_id']])->find()){
                return json(['code'=>202,'msg'=>'此订单不存在']);
            };
            $order = $this->order->find($data['order_id']);
            //查看是否重复填写
            if($this->order_user_info->where(['order_sn'=>$order->order_sn
                ,'user_id'=>$data['user_id']])->find()){
                return json(['code'=>200,'msg'=>'请勿重复填写']);
            }

            $this->order_user_info->save(['order_sn'=>$order->order_sn
                ,'user_name'=>$data['user_name'],
                'parent'=>$data['parent'],
                'order_id'=>$data['order_id'],
                'id_card'=>$data['id_card'],
                'age'=>$data['age'],
                'mobile'=>$data['mobile'],
                'school'=>$data['school']
                ,'user_id'=>$data['user_id'],
                'type'=>$order->type
            ]);
            return json(['code'=>200,'msg'=>'提交成功']);
        }catch (\Exception $exception){

            return json(['code'=>202,'msg'=>'提交失败','data'=>$exception->getMessage()]);
        }
    }


    /*订单详情*/
    public function order_detail(Request $request){

        $data = $request->param();
        $info = $this->order->with(['Goods','user_info'])->find($data['order_id']);
        if($info->type==1){//线下课程
            $info->goods =$info->nets;
        }
        //是否填写信息
        if($this->order_user_info->where('order_sn',$info->order_sn)->find()){
            $info->is_write_info=1;
        }else{
            $info->is_write_info=0;
        }
        return json(['code'=>200,'msg'=>'返回成功','data'=>['info'=>$info]]);

    }

    /*购买线上课程*/
    public function buy_net(Request $request){

        // file_put_contents("test.txt", "Hello world everyone.".PHP_EOL, FILE_APPEND);
        $data = $request->param('');
        $prefix = date('Ymd');
        $userInfo =$this->user->find($request->user_id);
        //检查
        try{
            Db::startTrans();
            if(!$this->account->where(['type'=>1,'id'=>$data['goods_id'],'status'=>1])->find()){
                return json(['code'=>202,'msg'=>'此课程不存在或已下架']);
            }
            $info = $this->account->find($data['goods_id']);

            $data['user_id'] = $request->user_id;
            $data['type'] =1;
            $data['order_sn'] = $prefix.random_int(100000, 999999).$prefix;

            /*java接口数据*/
            /* $result['IttParty_Jrnl_No'] = '2020'.$data['order_sn'];
             $result['Cmdty_Ordr_No'] = $data['order_sn'];
             $result['TAmt'] = $data['amount'];
             $result['url'] = 'https://ahhfbdc.govpay.ccb.com/online/multipenpayment';

             $json['Fee_Itm_Prj_Amt'] = $data['amount'];
             $json['Cmdty_Ordr_No'] = $data['order_sn'];
             $json['Fee_Itm_Cd'] = 'bgt'.$data['order_sn'];;
             $json['SN'] = 1;
             $result['SendSubInBo1Str'] = [json_encode($json)];*/


            /*java接口数据*/

            //判断名额是否足够
            /*  if($info->alone_number < 1){
                  return json(['code'=>202,'msg'=>'此课程名额不足']);
              }*/
            //判断是积分兑换还是现金购买
            if($data['order_type'] == 3){//支付宝支付

                $data['pay_type'] =3;
                $data['amount'] = $request->param('amount');
                /*  $wechat_pay = new WechatPay;
                  $wechat_pay->index($data['order_sn'],$info->price);*/

                //   Net::where('id',$data['goods_id'])->decrement('alone_number',1);
                //增加销量
                /*  Net::where('id',$data['goods_id'])->increment('sale',1);

                  //增加积分
                  WxUsers::where('id',$request->user_id)->increment('integral',$request->amount);
                  //生成积分明细
                  IntegralDetail::create(['user_id'=>$request->user_id ,
                      'integral'=>$request->amount,'type'=>1,'description'=>'购买课程返积分']);*/
                /* $ali_pay = new AliPayController();

                 $ali_pay_info = $ali_pay->index($data['order_sn'],$info->price);*/
                // $ali_pay_info = $this->ali_pay->index($data['order_sn'],$info->price,0,0,1);
                $order = $this->order->save($data);
                Db::commit();
                $order_user_info = $this->order_user_info->where(['user_id'=>$data['user_id']])->order('create_time desc')->find();

                return json(['code'=>200,'msg'=>'生成成功','data'=>['order_id'=>$this->order->id,'order_user_info'=>$order_user_info/*,'info'=>$ali_pay_info*/]]);

                //return json(['code'=>200,'msg'=>'生成成功','data'=>[/*'java_data'=>$result'info'=>$ali_pay_info,*/'order_id'=>$this->order->id]]);

            }else{//积分兑换
                $data['amount'] = $info->integral;
                if($info->integral > $userInfo->integral){
                    return json(['code'=>202,'msg'=>'积分不足']);

                }
                //扣除库存
                $data['pay_type'] = 2;
                // Net::where('id',$data['goods_id'])->decrement('alone_number',1);
                //增加销量
                $this->account->where('id',$data['goods_id'])->inc('sale',1);
                //扣除积分
                $this->user->where('id',$request->user_id)->dec('integral',$info->integral)->update();
                //生成积分明细
                $this->integral_detail->save(['user_id'=>$request->user_id ,
                    'integral'=>$info->integral,'type'=>0,'description'=>'积分兑换课程']);

            }

            $order = $this->order->save($data);
            /*设置课程用户拥有*/
            $this->user_net->save(['user_id'=>$request->user_id,
                'net_id'=>$request->param('goods_id'),'type'=>1,'create_time'=>time()]);
            Db::table('order')->where('order_sn',$data['order_sn'])->save(['status'=>1]);
            $order_user_info = $this->order_user_info->where(['user_id'=>$data['user_id']])->order('create_time,desc')->find();
            Db::commit();
            return json(['code'=>200,'msg'=>'生成成功','data'=>['order_user_info'=>$order_user_info,'order_id'=>$this->order->id]]);
        }catch (\Exception $exception){
            Db::rollback();
            return json(['code'=>202,'msg'=>'生成失败','data'=>$exception->getMessage()]);
        }
    }



    //重新发起退款
    public function re_refund($id){
        $order_info = $this->order->find($id);

        //查看是否已提交过退款
        if($order_info->Rfnd_TrcNo !=''){


            //查询退款状态
            $refund_info['Rfnd_TrcNo'] = $order_info->Rfnd_TrcNo;; //退款流水号

            $refund_info['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundinquiry';
            $refund_info['Sgn_Algr'] = 'SHA256withRSA';
            $refund_info['VNo'] = '3';
            $result_refund =  $this->curl->curl('47.114.152.142:8083/pay/refundinquiry',$refund_info); //提交退款查询单

            if($result_refund['resultCode'] ==200)
            {
                $data_refund_result = json_decode($result_refund['data'],true);//解析返回的data数据

                if($data_refund_result['Rfnd_StCd'] == '4'){

                    /*处理退款逻辑*/

                    /*主团结束*/

                    //获取当前group_id


                    //$list = $this->group_join->where('master_id',$group_info->id)->select()->toArray();

                    if($order_info->status !=6){
                        /*订单关闭*/
                        if($order_info->is_group ==1){ //如果是拼团订单
                            $this->group_master->where('id',$id)->update(['is_over'=>2]);
                            $this->group_join->where('id',$order_info->group_id)->update(['is_over'=>2]);
                            $order_info->save(['status'=>6,'is_refund'=>1]);
                        }else{ //单独购买订单
                            $order_info->save(['status'=>3,'is_refund'=>1]);
                        }
                        if($order_info->sku_id !=''){ //规格存在  规格库存回退
                            $this->account_item->where('id',$order_info->sku_id)->inc('number',1)->update();
                        }

                        /*商品库存返回*/
                        $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
                        $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();
                        $user_net = $this->user_net->where(['user_id' => $order_info->user_id,'net_id' => $order_info->goods_id ])->find();
                        $user_net && $user_net->delete();
                        return json(['code'=>200,'msg'=>'退款成功了']);
                    }

                }
            }
    }
    }
    /*建行申请退款*/
    public function test_refund($id/*Request $request*/)
    {
       
        $list= $this->order->where('master_group_id',$id)->column('id');
        //$list =['671'];

        foreach($list as $k=>$v){

            $order_info = $this->order->find($v);

            //查看是否已提交过退款
            if($order_info->Rfnd_TrcNo !=''){


                //查询退款状态
                $refund_info['Rfnd_TrcNo'] = $order_info->Rfnd_TrcNo;; //退款流水号

                $refund_info['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundinquiry';
                $refund_info['Sgn_Algr'] = 'SHA256withRSA';
                $refund_info['VNo'] = '3';
                $result_refund =  $this->curl->curl('47.114.152.142:8083/pay/refundinquiry',$refund_info); //提交退款查询单

                if($result_refund['resultCode'] ==200)
                {
                    $data_refund_result = json_decode($result_refund['data'],true);//解析返回的data数据

                    if($data_refund_result['Rfnd_StCd'] == '4'){

                        /*处理退款逻辑*/

                        /*主团结束*/

                        //获取当前group_id

                        $this->group_master->where('id',$id)->update(['is_over'=>2]);
                        $this->group_join->where('id',$order_info->group_id)->update(['is_over'=>2]);
                        //$list = $this->group_join->where('master_id',$group_info->id)->select()->toArray();

                        if($order_info->status !=6){
                            /*订单关闭*/
                            $order_info->save(['status'=>6,'is_refund'=>1]);

                            /*商品库存返回*/
                            $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
                            $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();


                            return json(['code'=>200,'msg'=>'退款成功']);
                        }
                        /*处理退款逻辑*/

                    }
                }
            }else{ //初次提交退款申请单
                $data['VNo'] = '3';
                $data['IttParty_Jrnl_No'] = $order_info->py_Ordr_No.rand(000,999); //随机生成的退款流水号 。不允许重复
                $data['Py_Ordr_No'] = $order_info->py_Ordr_No; //支付流水号
                $data['Rfnd_Amt'] = $order_info->amount; //金额
                $data['Rfnd_RDsc'] = '拼团失败退款'; //说明
                $data['Sgn_Algr'] = 'SHA256withRSA'; //签名算法
                $data['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundapply'; //请求申请退款地址

                $result =  $this->curl->curl('47.114.152.142:8083/pay/refundapply',$data); //提交退款申请单


                if($result['resultCode'] ==200)
                {

                    $data_refund = json_decode($result['data'],true);//解析返回的data数据
                    //获取退款申请号
                   // if($data_refund['Rfnd_StCd'] == '1'){ //退款查询
                        $refund_info['Rfnd_TrcNo'] = $data_refund['Rfnd_TrcNo']; //退款流水号
                        $order_info->save(['Rfnd_TrcNo'=>$refund_info['Rfnd_TrcNo']]);

                        $refund_info['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundinquiry';
                        $refund_info['Sgn_Algr'] = 'SHA256withRSA';
                        $refund_info['VNo'] = '3';
                        $result_refund =  $this->curl->curl('47.114.152.142:8083/pay/refundinquiry',$refund_info); //提交退款查询单

                        if($result_refund['resultCode'] ==200)
                        {
                            $data_refund_result = json_decode($result_refund['data'],true);//解析返回的data数据

                            //if($data_refund_result['Rfnd_StCd'] == '4'){

                                /*处理退款逻辑*/

                                /*主团结束*/

                                //获取当前group_id

                                $this->group_master->where('id',$id)->update(['is_over'=>2]);
                                $this->group_join->where('id',$order_info->group_id)->update(['is_over'=>2]);
                                //$list = $this->group_join->where('master_id',$group_info->id)->select()->toArray();

                                if($order_info->status !=6){
                                    /*订单关闭*/
                                    $order_info->save(['status'=>6,'is_refund'=>1]);
                                    if($order_info->sku_id !=''){ //规格存在  规格库存回退
                                        $this->account_item->where('id',$order_info->sku_id)->inc('number',1)->update();
                                    }
                                    /*商品库存返回*/
                                    $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
                                    $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();


                                    return json(['code'=>200,'msg'=>'退款成功']);
                                }
                                /*处理退款逻辑*/

                           /* }else{
                                $this->re_refund($v);
                            }*/
                        }
                   // }
                }




            }
            return json(['code'=>202,'msg'=>'退款失败']);
        }
    }


    /**
     * 非团购课程订单申请退款
     * @param Request $request
     * @return \think\response\Json
     */
    public function up_refund(Request $request)
    {
        $order_info = $this->order->find($request->param('order_id'));
        $no_msg = $this->configuration->where('key','refund')->value('val');


        if($order_info->status ==5){
            return json(['code'=>202,'msg'=>$no_msg]);
        }

        if($order_info->status !=1 || $order_info->is_group ==1)
        {
            return json(['code'=>202,'msg'=>'订单状态异常不允许退款']);
        }
        //初次提交退款申请单
        $data['VNo'] = '3';
        $data['IttParty_Jrnl_No'] = $order_info->py_Ordr_No.rand(000,999); //随机生成的退款流水号 。不允许重复
        $data['Py_Ordr_No'] = $order_info->py_Ordr_No; //支付流水号
        $data['Rfnd_Amt'] = $order_info->amount; //金额
        $data['Rfnd_RDsc'] = '课程退款'; //说明
        $data['Sgn_Algr'] = 'SHA256withRSA'; //签名算法
        $data['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundapply'; //请求申请退款地址

        $result =  $this->curl->curl('47.114.152.142:8083/pay/refundapply',$data); //提交退款申请单


        if($result['resultCode'] ==200)
        {

            $data_refund = json_decode($result['data'],true);//解析返回的data数据
            //获取退款申请号

            $refund_info['Rfnd_TrcNo'] = $data_refund['Rfnd_TrcNo']; //退款流水号

            $order_info->save(['Rfnd_TrcNo'=>$refund_info['Rfnd_TrcNo'],'status'=>3]);

            if($order_info->sku_id !=''){ //规格存在  规格库存回退
                $this->account_item->where('id',$order_info->sku_id)->inc('number',1)->update();
            }

            /*商品库存返回*/
            $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
            $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();
            $user_net = $this->user_net->where(['user_id' => $order_info->user_id,'net_id' => $order_info->goods_id ])->find();
            $user_net && $user_net->delete();
            $refund_info['url'] = 'https://zjjxdcw.govpay.ccb.com/online/refundinquiry';
            $refund_info['Sgn_Algr'] = 'SHA256withRSA';
            $refund_info['VNo'] = '3';
            $result_refund =  $this->curl->curl('47.114.152.142:8083/pay/refundinquiry',$refund_info); //提交退款查询单

            if($result_refund['resultCode'] ==200)
            {
                $data_refund_result = json_decode($result_refund['data'],true);//解析返回的data数据

                if($data_refund_result['Rfnd_StCd'] == '4'){

                    /*处理退款逻辑*/

                    /*主团结束*/

                    //获取当前group_id

                    //$this->group_master->where('id',$id)->update(['is_over'=>2]);
                    //$this->group_join->where('id',$order_info->group_id)->update(['is_over'=>2]);
                    //$list = $this->group_join->where('master_id',$group_info->id)->select()->toArray();

                    if($order_info->status !=6){
                        /*订单关闭*/
                        $order_info->save(['status'=>6,'is_refund'=>1]);

                        /*商品库存返回*/
                        $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
                        $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();


                        return json(['code'=>200,'msg'=>'退款成功']);
                    }
                    /*处理退款逻辑*/

                }else{
                    return json(['code'=>200,'msg'=>'退款将原路退回，请注意查收']);
               }
            }else{
                $this->re_refund($request->param('order_id'));
            }

        }else{
            return json(['code'=>202,'服务器异常']);
        }
    }
    /*拼团结束订单退款*/
    public function refund($id){

        $list= $this->order->where('master_group_id',$id)->column('id');
        foreach($list as $k=>$v){
            $this->ali_pay->refund($v);
            /*主团结束*/
            $order_info = $this->order->find($v);
            //获取当前group_id

            //$group_info = $this->group_master->find(master_group_id);
            $this->group_master->where('id',$id)->update(['is_over'=>2]);
            $this->group_join->where('id',$order_info->group_id)->update(['is_over'=>2]);
            //$list = $this->group_join->where('master_id',$group_info->id)->select()->toArray();


            if($order_info->status !=6){
                /*订单关闭*/
                $order_info->save(['status'=>6]);

                /*商品库存返回*/
                $this->account->where('id',$order_info->goods_id)->dec('sale',1)->update();
                $this->account->where('id',$order_info->goods_id)->inc('alone_number',1)->update();


                return json(['code'=>200,'msg'=>'退款成功']);
            }


            return json(['code'=>202,'msg'=>'退款失败']);
        }


    }

    //订单列表
    public function order(Request $request){
        $model = $this->order;
        if($request->param('cate') == 0){

            $res = $model->where(['user_id'=>$request->user_id,'type'=>0])->with('Goods')->order('create_time','desc')
                ->paginate($request->param('limit',10));
        }else{
            $res = $model->where(['user_id'=>$request->user_id,'type'=>$request->param('cate',0)])->with('Goods')->order('create_time','desc')
                ->paginate($request->param('limit',10));
        }
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }



    //发布订单评价
    public function push_comment(Request $request){
        try{
            Db::startTrans();
            $order = $this->order->find($request->param('order_id'));
            $this->order_comment->save(['content'=>$request->param('content'),
                'create_time'=>time(),'store_id'=>$order->store_id,'user_id'=>$request->user_id,'images'=>@$request->param('images'),
                'order_id'=>$request->param('order_id'),'type'=>$order->type,'start'=>$request->param('start'),'goods_id'=>$order->goods_id]);
            $this->order->where('id',$request->param('order_id'))->update(['status'=>4]);

            //增加积分
            Db::name('wx_users')->where('id', $order->user_id)->inc('integral', $order->amount)->update();
            //生成积分明细
            Db::name('integral_detail')->insert(['user_id' => $order->user_id,
                'integral' => $order->amount, 'type' => 1, 'description' => '购买课程返积分']);
            //商家星级评选
            $start = $this->order_comment->where('store_id',$order->store_id)->avg('start');
            // Store::where('id',$order->store_id)->update(['start'=>$start]);
            Db::commit();
            return json(['code'=>200,'msg'=>'生成成功']);
        }catch(\Exception $exception){
            Db::rollBack();
            return json(['code'=>202,'msg'=>'生成失败','data'=>$exception->getMessage()]);
        }
    }


    /*我的评价*/
    public function my_comment(Request $request){


        if($request->param('type') ==1){
            $model = $this->order_comment;
            $res = $model->where(['user_id'=>$request->user_id])->with(['user','goods'])->order('create_time','desc')
                ->paginate($request->param('limit',10));
        }else{
            $model = $this->comment;
            $res = $model->where(['from_uid'=>$request->user_id])->with(['user','topic'])->order('create_time','desc')
                ->paginate($request->param('limit',10));
        }

        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /*删除评价*/
    public function del_comment(Request $request){

        try{
            if($request->param('type') ==1){
                $model = $this->order_comment;
                $res = $model->where(['user_id'=>$request->user_id,'id'=>$request->param('id')])->find();
                $res && $res->delete();
            }elseif($request->param('type') ==3){
                $model = $this->topic;
                $res = $model->where(['user_id'=>$request->user_id,'id'=>$request->param('id')])->find();
                $res && $res->delete();
            }else{

                $res = $this->comment->where(['from_uid'=>$request->user_id,'id'=>$request->param('id')])->find();
                $res && $res->delete();
                //dd($this->comment->getLastSql());
            }

            return json(['code'=>200,'msg'=>'删除成功']);
        }catch(\Exception $e)
        {
            return json(['code'=>202,'msg'=>'失败','error'=>$e->getMessage()]);
        }




    }


    //支付宝支付回调
    public function notify()
    {

        $xmldata = file_get_contents("php://input");
        //file_put_contents("test.txt", $this->request->param(), FILE_APPEND);
        //$xmldata = 'gmt_create=2020-07-17+15%3A03%3A52&charset=UTF-8&seller_email=hnscmzx%40163.com&subject=BI8EJM+Alipay+%E6%B5%8B%E8%AF%95&sign=YpjnvWTsv19M%2B2Y9U0d8E6ijj7cYpHRU3lQtEZ%2FJYYd2gEmMejpTUPcj4gVqlg9CXN0PyP8KTRJGuuFy7bIvxPT7XwFnIiqc0FCxP2CxihbPtll2BjlGqiSop3v1Z%2BxEBG5AFDUzHdzr2hkiu3nRFPtumoYh3z83N0R7U0KvBwWLOsmI2DqlfzyO9E7xILVTfo3SEKGg41AwBOTA%2BLKkKfdbDekoM1ftAkkYlIdLp4Jd9gfedrF2n%2BeDWMN0jble9Z7qORhZbv23z%2BdyhO3EbQuIV6aUZIcx0TY5pCbZRXn8p9VmEjcKj9goUxD52QDTqvVrupvdkLd5dQnCaWDDxQ%3D%3D&buyer_id=2088612292754732&invoice_amount=0.01&notify_id=2020071700222150353054731450640551&fund_bill_list=%5B%7B%22amount%22%3A%220.01%22%2C%22fundChannel%22%3A%22PCREDIT%22%7D%5D&notify_type=trade_status_sync&trade_status=TRADE_SUCCESS&receipt_amount=0.01&buyer_pay_amount=0.01&app_id=2021001162643463&sign_type=RSA2&seller_id=2088731738672954&gmt_payment=2020-07-17+15%3A03%3A52&notify_time=2020-07-17+15%3A03%3A53&version=1.0&out_trade_no=2020071758698920200717&total_amount=0.01&trade_no=2020071722001454731433666927&auth_app_id=2021001162643463&buyer_logon_id=157****5118&point_amount=0.00';
        $data_result = explode('&',$xmldata);

        foreach($data_result as $k=>$v){
            $val = explode('=',$v);
            $datas[$k][reset($val)] = end($val);
        }
        function merge_array($array){
            return call_user_func_array('array_merge',$array);
        }
        $data = merge_array($datas);

        $aop = app('alipay\aop\AopClient');
        $wap = app('alipay\aop\request\AlipayTradeWapPayRequest');
        /*$da = '2020-07-17 18:21:16UTF-8hnscmzx@163.comBI8EJM Alipay 测试AGALZnYhkmfSyW3Y84/vYQolySIhHU1t254eAT+oAiebkkWTrVgocIkJtMJPwjxS+gmTLZDcp2ukg/cpCgh4IZvAlxm2Njoql6zGXMqMtJ/DoFgV818eyaqGgFkhvonz4AZp8azUIn0yQx2YnNAR7ZMSl8fYwbzC3kzxwTjeFbQ3ER2tfCXMMKKiNJ8OXigKu30HrgqvmFC+uV4W5zM2m3ASOCILsmQx/9h/4wBH5D9N8LtaK9o6VsNj7z6j8U7zGeN2C9PcaelWYBxgZfDxQzi6iVftUbDQh/kPg3TCYy23oyiUJj7p8QrcjF3jKPQIjk8lpj7LbxZYQWdFwRi5HQ==20886122927547320.012020071700222182117054731450812436[{"amount":"0.01","fundChannel":"PCREDIT"}]trade_status_syncTRADE_SUCCESS0.010.012021001162643463RSA220887317386729542020-07-17 18:21:172020-07-17 18:21:171.020200717752264202007170.0120200717220014547314336232322021001162643463157****51180.002020071758698920200717';
        */  $data = json_decode(json_encode($data),true);
        //file_put_contents("test.txt", $this->request->param(), FILE_APPEND);
        //$aop->alipayrsaPublicKey = $this->ali_pay->get_alipay()['public_key'];
        //$flag = $aop->rsaCheckV1($data,NULL,"RSA2");     //验签

        //if($data['trade_status']=='TRADE_SUCCESS')     //支付状态
        if(true)     //支付状态
        {
            //$data['out_trade_no'] = file_get_contents("test.txt");

            //file_put_contents("test.txt", $data['trade_no'].'|', FILE_APPEND);
            //file_put_contents("test.txt", $data['out_trade_no'].'|', FILE_APPEND);

            try {
                $order_no = $data['out_trade_no'];
                //file_put_contents("test.txt", $order_no.'|', FILE_APPEND);

                $order_info = Db::name('order')->where('order_sn', $order_no)->find();
                //file_put_contents("test.txt", $order_info['type'], FILE_APPEND);

                Db::name('order')->where('order_sn',$order_no)->update(['alipay_trade_no'=>$data['trade_no']]);
                if ($order_info['type'] == 1) {//网上课程
                    $data['amount'] = $order_info['amount'];
                    // Net::where('id',$data['goods_id'])->decrement('alone_number',1);
                    //增加销量
                    Db::name('account')->where('id', $order_info['goods_id'])->inc('sale', 1)->update();

                    //增加积分
                    Db::name('wx_users')->where('id', $order_info['user_id'])->inc('integral', $order_info['amount'])->update();
                    //生成积分明细
                    Db::name('integral_detail')->insert(['user_id' => $order_info['user_id'],
                        'integral' => $order_info['amount'], 'type' => 1, 'description' => '购买课程返积分']);
                    Db::name('user_net')->insert(['user_id' => $order_info['user_id'],
                        'net_id' => $order_info['goods_id'], 'type' => 1, 'create_time' => time()]);
                    Db::name('order')->where('order_sn', $order_info['order_sn'])->update(['status' => 1]);
                } else {//线下课程
                    $info = Db::name('account')->find($order_info['goods_id']);

                    //主团id
                    $group_id = $order_info['master_group_id'];

                    if ($order_info['is_group'] == 1 && ($order_info['group_id'] == $order_info['master_group_id'])) { //开团

                        /* //发起团
                         $group_id = Db::name('group_master')->insertGetId(['order_sn' => $data['order_sn'],
                             'user_id' => $order_info->user_id, 'goods_id' => $order_info['goods_id'], 'total_number' => $info['num'],
                             'join_number' => 1, 'is_over' => 0,
                         ]);*/
                        //自己参团
                        /*Db::name('group_join')->insert(['order_sn' => $data['order_sn'],
                            'user_id' => $order_info['user_id'], 'master_id' => $group_id
                        ]);*/

                        Db::name('order')->where('order_sn', $order_no)->update(['status' => 0]);
                    } else if ($order_info['is_group'] == 1  && $order_info['group_id'] > 0 && $order_info['group_id'] != $order_info['master_group_id']) { //参团

                        //判断当前团是否自己的
                        /*if (Db::name('group_master')->where(['user_id' => $order_info['user_id'], 'id' => $group_id])->find()) {
                            return json(['code' => 202, 'msg' => '无法参加自己的团']);
                        }*/

                        //判断这个团是否已结束
                        /* if (Db::name('group_master')->where(['id' => $group_id, 'is_over' =>['neq',0]])->find()) {
                             return json(['code' => 202, 'msg' => '当前团已结束或不存在']);
                         }*/
                        //参团
                        /* Db::name('group_join')->insert(['order_sn' => $order_info->order_sn,
                             'user_id' => $order_info->user_id, 'master_id' => $group_id
                         ]);*/
                        //Db::name('group_master')->where('id',$group_id)->inc('join_number')->update();
                        //查看是否团购人数已满。团成功并结束
                        $group_info = Db::name('group_master')->where('id', $group_id)->field('join_number,total_number')->find();
                        Db::name('order')->where('order_sn', $order_no)->update(['status' => 0]);
                        if ($group_info['join_number'] >= $group_info['total_number']) {
                            Db::name('group_master')->where('id', $data['group_id'])->update(['is_over' => 1]);
                            //修改订单状态
                            $list = Db::name('group_join')->where('master_id', $data['group_id'])->select();

                            foreach ($list as $k => $v) {
                                /*设置课程用户拥有*/
                                Db::name('user_net')->insert(['user_id' => $v['user_id'],
                                    'net_id' => $order_info['goods_id'], 'type' => 0]);

                                Db::name('order')->where('order_sn',$v['order_no'])->update(['status' =>1]);
                            };
                        }
                    } else if($order_info['group_id'] == 0 && $order_info['is_group'] == 0) {//单独购买

                        //file_put_contents("test.txt", $data['trade_no'], FILE_APPEND);
                        /*设置课程用户拥有*/
//                    $this->user_net->save(['user_id' => $order_info['user_id'],
//                        'net_id' => $order_info['goods_id'], 'type' => 0]);
                        //dd($order_info);
                        Db::name('order')->where('order_sn',$order_no)->update(['status' =>1]);

                    }

                }

            } catch (\Exception $e) {

            }

        }
    }

}